<?php
declare (strict_types=1);

namespace app\platform\validate;

use think\Validate;

class Website extends Validate
{
    protected $rule = [
        'name'           => 'require',
        'code'           => 'require|checkExistCode',
        'db_host'        => 'require',
        'db_port'        => 'require',
        'db_user'        => 'require',
        'db_password'    => 'require',
        'domain'         => 'require',
        'frontend_url'   => 'require',
        'backend_url'    => 'require',
        'app_id'         => 'require',
        'app_secret'     => 'require',
        'app_jwt_secret' => 'require',
        'website_type'   => ['require', 'in' => '1,2,3'],
        'status'         => ['require', 'in' => '1,2'],
    ];

    protected $message = [
        'name.require'           => '请输入站点名称',
        'code.require'           => '请输入站点标识',
        'db_host.require'        => '请输入数据库连接地址',
        'db_port.require'        => '请输入数据库连接端口',
        'db_user.require'        => '请输入数据库用户名',
        'db_password.require'    => '请输入数据库密码',
        'domain.require'         => '请输入站点域名',
        'frontend_url.require'   => '请输入前台访问地址',
        'backend_url.require'    => '请输入后台访问地址',
        'app_id.require'         => '请输入 app id',
        'app_secret.require'     => '请输入 app secret',
        'app_jwt_secret.require' => '请输入 app jwt secret',
        'website_type'           => '请选择正确的网站类型',
        'status'                 => '请选择正确的状态',
    ];

    protected $scene = [
        'add'  => [
            'name',
            'status',
            'code',
            'domain',
            'frontend_url',
            'backend_url',
            'app_id',
            'app_secret',
            'app_jwt_secret',
            'db_host',
            'db_user',
            'db_port',
            'db_password',
        ],
        'edit' => [
            'name',
            'status',
            'domain',
            'frontend_url',
            'backend_url',
            'app_id',
            'app_secret',
            'app_jwt_secret',
            'db_host',
            'db_user',
            'db_port',
        ],
    ];

    public function checkExistCode($value, $rule, $data = [])
    {
        $websiteModel = new \app\common\model\Website();
        $websiteObj = $websiteModel->findWebsiteByCode($value);
        if (!empty($websiteObj)) {
            $website = $websiteObj->toArray();
            if(isset($data['id']) && $website['id']!=$data['id']){
                return '站点标识已存在';
            }
        }

        return true;
    }
}
